﻿using Infragistics.WebUI.UltraWebGrid;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using uMES.LeanManufacturing.ParameterDTO;
using uMES.LeanManufacturing.ReportBusiness;

public partial class Custom_BwPlanManager_BwContainerStartPopupForm : BaseForm
{
    uMESContainerBusiness containerBal = new uMESContainerBusiness();
    uMESCommonBusiness commonBal = new uMESCommonBusiness();

    string businessName = "批次管理", parentName = "Container";
    protected override void OnInit(System.EventArgs e)
    {
        base.OnInit(e);
       
        var bas = new HtmlGenericControl("base");
        bas.Attributes["target"] = "_self";
        Header.Controls.Add(bas);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        lStatusMessage.Text = "";
        getProductInfo.GetProductData += new GetProductInfo_ascx.GetProductDataEventHandler(LoadProductData);
        getWorkFlowInfo.GetWorkFlowData+= new GetWorkFlowInfo_ascx.GetWorkFlowDataEventHandler(LoadWorkflowData);
        getProductInfo.DDlProductDataChanged += new GetProductInfo_ascx.DDlProductDataChangedEventHandler(DDlProductDataChanged);

        if (IsPostBack==false)
        {
            DataTable dt = PopupData as DataTable;
            Session.Remove("PopupData");

            containerBal.dealPopupDt(ref dt);
            
            gdMfgorder.DataSource = dt;
            gdMfgorder.DataBind();

            InitControl(dt);
            InintContainerNo();

            string strQty = gdMfgorder.Rows[0].Cells.FromKey("Qty").Text;
            txtQty.Text = strQty;

            try
            {
                string strStartDate = Convert.ToDateTime(gdMfgorder.Rows[0].Cells.FromKey("PlannedStartDate").Text).ToString("yyyy-MM-dd");
                txtPlannedstartdate.Value = System.DateTime.Now.ToString("yyyy-MM-dd");// strStartDate;
            }
            catch
            { }

            try
            {
                string strEndDate = Convert.ToDateTime(gdMfgorder.Rows[0].Cells.FromKey("PlannedCompletionDate").Text).ToString("yyyy-MM-dd");
                txtPlannedcompletiondate.Value = strEndDate;
            }
            catch
            { }
        }
    }


    #region 事件

    protected void CloseButton_Click(object sender, EventArgs e)
    {
        Dictionary<string, string> returnToMain = new Dictionary<string, string>();

        returnToMain["Page"] = "BwContainerBatchStartPopupForm.aspx";
        PopupData = returnToMain;
        ClosePopupPage(false);
      // ClientScript.RegisterStartupScript(this.GetType(), "NotifyParent", "<script> window.returnValue = true; window.close();</script> ");
    }

    protected void btnAll_Click(object sender, EventArgs e)
    {
        uMESCommonFunction.ResetGridCheckStatus(gdSubContainerNo, "ckSelect", 0);
    }

    protected void btnNotAll_Click(object sender, EventArgs e)
    {
        uMESCommonFunction.ResetGridCheckStatus(gdSubContainerNo, "ckSelect", 2);
    }

    protected void btnDel_Click(object sender, EventArgs e)
    {
        for (int i=gdSubContainerNo.Rows.Count-1; i>=0; i--)
        {

            if (gdSubContainerNo.Rows[i].Cells.FromKey("ckSelect").Text.ToLower()== "true")
            {
                gdSubContainerNo.Rows.Remove(gdSubContainerNo.Rows[i]);
             
            }

        }
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        gdSubContainerNo.Rows.Clear();
        string containerNo = txtContainerNo.Text;
        if (string.IsNullOrWhiteSpace(containerNo))
        {
            DisplayMessage(lStatusMessage,"批次号不能为空", false);
            return;
        }
        if (string.IsNullOrWhiteSpace(txtQty.Text))
        {
            DisplayMessage(lStatusMessage, "数量不能为空", false);
            return;
        }

        if (string.IsNullOrWhiteSpace(txtStartSubNo.Text))
        {
            DisplayMessage(lStatusMessage, "起始序号数量不能为空", false);
            return;
        }
        if (string.IsNullOrWhiteSpace(getProductInfo.GetProductDDL.SelectedValue))
        {
            DisplayMessage(lStatusMessage, "产品不能为空", false);
            return;
        }


        int count = int.Parse(txtQty.Text);
        int startSubNo = int.Parse(txtStartSubNo.Text);

        DataTable dt = new DataTable();
        dt.Columns.Add("SubContainerNo");

        string productName = "", productRev = "";

        GetProductInfo(ref productName,ref productRev);

        for (int i = 0; i < count; i++)
        {
            DataRow dr = dt.NewRow();
            string tempSubNo = productName + "/" + containerNo + (startSubNo + i).ToString("D3");
            dr["SubContainerNo"] = tempSubNo;
            dt.Rows.Add(dr);
        }
        gdSubContainerNo.DataSource = dt;
        gdSubContainerNo.DataBind();
    }
    //批次创建
    protected void btnStart_Click(object sender, EventArgs e)
    {
        try {

            ResultModel re = StartContainer();
            if (re.IsSuccess)
            // InintContainerNo();
            {
                //批次开卡完成，增加记录
                #region 日志赋值
                //获取批次id
                var temp = containerBal.GetTableInfo("Container","ContainerName", re.Data.ToString());
                if (temp.Rows.Count > 0)
                {
                    MESAuditLog ml = new MESAuditLog();
                    ml.ContainerName = re.Data.ToString();ml.ContainerID= temp.Rows[0]["ContainerID"].ToString();
                    ml.ParentID = temp.Rows[0]["ContainerID"].ToString(); ml.ParentName = parentName;
                    ml.CreateEmployeeID = UserInfo["EmployeeID"];
                    ml.BusinessName = businessName; ml.OperationType = 0;
                    ml.Description = "批次创建:" + ml.ContainerName + "创建成功,数量:"+temp.Rows[0]["Qty"].ToString();
                    commonBal.SaveMESAuditLog(ml);

                }
                #endregion
                //
                Dictionary<string, string> returnToMain = new Dictionary<string, string>();

                returnToMain["Page"] = "BwContainerBatchStartPopupForm.aspx";
                PopupData = returnToMain;
                ClosePopupPage(true);
            }
            DisplayMessage(lStatusMessage, re.Message, re.IsSuccess);
        } catch (Exception ex) {
            DisplayMessage(lStatusMessage, ex.Message, false);
        }
    }
    #endregion


    #region 方法
    void InitControl(DataTable dt)
    {
        DataTable ddlDt = containerBal.GetTableInfo("startreason", null, null);
        ddlStartReason.DataTextField = "startreasonname";
        ddlStartReason.DataValueField = "startreasonid";
        ddlStartReason.DataSource = ddlDt;
        ddlStartReason.DataBind();

        ddlDt = containerBal.GetTableInfo("containerlevel", null, null);
        ddlContainerLevel.DataTextField = "containerlevelname";
        ddlContainerLevel.DataValueField = "containerlevelid";
        ddlContainerLevel.DataSource = ddlDt;
        ddlContainerLevel.DataBind();

        ddlDt = containerBal.GetTableInfo("owner", null, null);
        ddlOwner.DataTextField = "ownername";
        ddlOwner.DataValueField = "ownerid";
        ddlOwner.DataSource = ddlDt;
        ddlOwner.DataBind();

        ddlDt = containerBal.GetTableInfo("Uom", null, null);
        ddlUom.DataTextField = "UomName";
        ddlUom.DataValueField = "UomId";
        ddlUom.DataSource = ddlDt;
        ddlUom.DataBind();

            

        // 默认选择产品
        string productName = dt.Rows[0]["ProductName"].ToString();
        string productId= dt.Rows[0]["ProductID"].ToString();

        getProductInfo.GetProductNameOrTypeText.Text=productName;
        getProductInfo.DoSearchProductInfo();
        getProductInfo.GetProductDDL.SelectedValue = productId;

        //加载默认工艺
        DDlProductDataChanged();

        ////批次号
        //string productInfo = getProductInfo.ProducText;

        // productName = productInfo.Substring(0, productInfo.IndexOf(":"));
        //string year = DateTime.Now.Year.ToString();
        //year = year.Substring(year.Length - 2, 2);
        //int nexNo = containerBal.GetNewContainerNextNo(productName + "/" + year);
        //txtContainerNo.Text = year.ToString() + nexNo.ToString("D2");

        //int nextSubNo = containerBal.GetNewChildContainerNextNo(productName + "/" + txtContainerNo.Text);
        //txtStartSubNo.Text = nextSubNo.ToString("D3");
        


    }
    /// <summary>
    /// 初始化批次号
    /// </summary>
   void InintContainerNo()
    {  //批次号
       string productName = "",productRev="";

        GetProductInfo(ref productName,ref productRev);

        string year = DateTime.Now.Year.ToString();
        year = year.Substring(year.Length - 2, 2);
        int nexNo = containerBal.GetNewContainerNextNo(productName + "/" + year);

        txtContainerYearNo.Text = year.ToString();
        txtContainerNo.Text = nexNo.ToString("D2");
        

        int nextSubNo = containerBal.GetNewChildContainerNextNo(productName + "/" + year.ToString() + txtContainerNo.Text);
        txtStartSubNo.Text = nextSubNo.ToString("D3");

    }

    void LoadProductData(){
        if (getProductInfo.Message.Length > 0)
        {
            DisplayMessage(lStatusMessage,getProductInfo.Message,false);
        }
       }

    void LoadWorkflowData()
    {
        if (getWorkFlowInfo.Message.Length > 0)
        {
            DisplayMessage(lStatusMessage, getWorkFlowInfo.Message, false);
        }
    }
    /// <summary>
    /// 件号更改带出工艺
    /// </summary>
    void DDlProductDataChanged()
    {
        getWorkFlowInfo.InitControl();

        string productName = "";

        string productRev = "";

        GetProductInfo(ref productName, ref productRev);

        if (productName == "")
        {
            return;
        }

        Dictionary<string, string> para = new Dictionary<string, string>();
        para["ProductName"] = productName;
        para["ProductRev"] = productRev;

        getWorkFlowInfo.SearchWorkFlow(para, 1);

    }

    /// <summary>
    /// 开卡
    /// </summary>
    /// <returns></returns>
    ResultModel StartContainer()
    {

        ResultModel result = new ResultModel(false, "");

        //必填项验证
        if (string.IsNullOrWhiteSpace(txtQty.Text))
        {
            result.Message = "请输入数量";
            return result;
        }

        if (string.IsNullOrWhiteSpace(getProductInfo.ProducText))
        {
            result.Message = "请选择产品";
            return result;
        }

        if (string.IsNullOrWhiteSpace(txtPlannedstartdate.Value))
        {
            result.Message = "请选择计划开始日期";
            return result;
        }

        if (string.IsNullOrWhiteSpace(getWorkFlowInfo.WorkFlowText))
        {
            result.Message = "请选择工艺流程";
            return result;
        }
        //

        if (Convert.ToInt32(txtQty.Text)>Convert.ToInt32(gdMfgorder.Rows[0].Cells.FromKey("Qty").Text)) {
            result.Message = "不能超过剩余可投数";
            return result;
        
        }

        string productName = "";
        string productRev = "";

        GetProductInfo(ref productName,ref productRev);


        ContainerStartModel containerStart = new ContainerStartModel();
        containerStart.ContainerName = productName + "/" +txtContainerYearNo.Text+ txtContainerNo.Text;
        containerStart.Level = ddlContainerLevel.SelectedItem.Text;
        containerStart.ProductName = productName;
        containerStart.ProductRev = productRev;

        containerStart.Owner = ddlOwner.SelectedItem.Text;
        containerStart.Qty = int.Parse(txtQty.Text);
        containerStart.Uom = ddlUom.SelectedItem.Text; //单位
        containerStart.StartReason =ddlStartReason.SelectedItem.Text;


        string workflowName = "", workflowRev = "";
        GetWorkflowInfo(ref workflowName, ref workflowRev);

        containerStart.WorkflowName = workflowName;
        containerStart.WorkflowRev = workflowRev;

        containerStart.Mfgorder =gdMfgorder.Rows[0].Cells.FromKey("MfgorderName").Text;

        if (!string.IsNullOrWhiteSpace(txtPlannedstartdate.Value)  || !string.IsNullOrWhiteSpace(txtPlannedcompletiondate.Value))
        {
            if (string.IsNullOrWhiteSpace(txtPlannedstartdate.Value) || string.IsNullOrWhiteSpace(txtPlannedcompletiondate.Value))
            {
                result.Message = "批次的计划开始和完成时间需同时存在";
                return result;
            }

            DateTime startDate, finishDate;
            if (!DateTime.TryParse(txtPlannedstartdate.Value, out startDate) || !DateTime.TryParse(txtPlannedcompletiondate.Value, out finishDate))
            {
                result.Message = "时间格式错误";
                return result;
            }
            if (startDate > finishDate)
            {
                result.Message = "批次的计划开始时间不能大于计划完成时间";
                return result;
            }
            containerStart.PlannedStartDate = startDate.ToString("yyyy-MM-dd HH:mm:ss");
            containerStart.PlannedCompletionDate = finishDate.Date.ToString("yyyy-MM-dd HH:mm:ss");

        }
        else
        {
            containerStart.PlannedStartDate = ""; containerStart.PlannedCompletionDate = "";
        }

        containerStart.ContainerComment = txtNotes.Text;
        //子批次
        DataTable childDt = new DataTable(); childDt.Columns.Add("ContainerName");
        childDt.Columns.Add("Qty"); childDt.Columns["Qty"].DefaultValue = 1;

            foreach (UltraGridRow dr in gdSubContainerNo.Rows)
            {
                var childRow = childDt.NewRow();
                childRow["ContainerName"] = dr.Cells.FromKey("SubContainerNo");
                childDt.Rows.Add(childRow);
            }
        

        childDt.AcceptChanges();
        containerStart.ChildList = childDt;
        containerStart.StartEmployee = UserInfo["EmployeeName"];

        //批次属性
        if (!string.IsNullOrWhiteSpace(gdMfgorder.Rows[0].Cells.FromKey("ReplaceMaterial").Text) && !string.IsNullOrWhiteSpace(gdMfgorder.Rows[0].Cells.FromKey("ReplaceMaterialName").Text)
           && !string.IsNullOrWhiteSpace(gdMfgorder.Rows[0].Cells.FromKey("ReplaceMaterialQty").Text))
        {
            DataTable attributeList = new DataTable();
            attributeList.Columns.Add("Name"); attributeList.Columns.Add("Value");

            DataRow attributeRow = attributeList.NewRow();
            attributeRow["Name"] = "代料规格型号";
            attributeRow["Value"] = gdMfgorder.Rows[0].Cells.FromKey("ReplaceMaterial").Text;
            attributeList.Rows.Add(attributeRow);

            attributeRow = attributeList.NewRow();
            attributeRow["Name"] = "代料名称";
            attributeRow["Value"] = gdMfgorder.Rows[0].Cells.FromKey("ReplaceMaterialName").Text;
            attributeList.Rows.Add(attributeRow);

            float qty = 0;float mfgQty = float.Parse(gdMfgorder.Rows[0].Cells.FromKey("MfgQty").Text);//MfgQty
            qty = containerStart.Qty*float.Parse(gdMfgorder.Rows[0].Cells.FromKey("ReplaceMaterialQty").Text) / mfgQty;
            attributeRow = attributeList.NewRow();
            attributeRow["Name"] = "代料数";
            attributeRow["Value"] = qty;
            attributeList.Rows.Add(attributeRow);

            containerStart.AttributeList = attributeList;
        }

        result = containerBal.StartContainer(containerStart, UserInfo["ApiEmployeeName"], UserInfo["ApiPassword"]);
        if (result.IsSuccess)
        { result.Message = "批次" + containerStart.ContainerName + "创建完成";
            result.Data = containerStart.ContainerName;
        }

        return result;


    }

    //获取产品名及版本
    void GetProductInfo(ref string productName, ref string productRev)
    {
        string productInfo = getProductInfo.ProducText;

        if (productInfo == "")
        {
            return;
        }

        productName = productInfo.Substring(0, productInfo.IndexOf(":"));
        productRev = productInfo.Substring(productInfo.IndexOf(":") + 1, productInfo.IndexOf("(", productName.Length) - productInfo.IndexOf(":") - 1);

    }

    //获取工艺名及版本
    void GetWorkflowInfo(ref string workflowName, ref string workflowRev)
    {
        string strWrokflow = getWorkFlowInfo.WorkFlowText;

        //workflowName = getWorkFlowInfo.WorkFlowText.Substring(0, strWrokflow.IndexOf(":"));

        //workflowRev = strWrokflow.Replace(strWrokflow, "");

        if (strWrokflow!=string.Empty || strWrokflow!="")
        {
            string[] array = strWrokflow.Split(':');

            workflowName = array[0];

            workflowRev = array[1];
        }
      

    }
    #endregion







}